package lhz.dlx.simple;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import lhz.RabbitMqUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: LiHuaZhi
 * @Date: 2021/10/20 20:30
 * @Description:
 **/
public class Consumer01 {

    // 路由
    private static final String ROUTING_KEY = "dlx";
    private static final String NORMAL_ROUTING_KEY = "normal";
    //普通交换机名称
    private static final String NORMAL_EXCHANGE = "normal_exchange";
    //死信交换机名称
    private static final String DEAD_EXCHANGE = "dead_exchange";

    public static void main(String[] args) throws Exception {
        // 获取Channel
        Channel channel = RabbitMqUtils.getChannel();

        // 声明死信和普通交换机   类型为  direct
        channel.exchangeDeclare(NORMAL_EXCHANGE, BuiltinExchangeType.DIRECT);
        channel.exchangeDeclare(DEAD_EXCHANGE, BuiltinExchangeType.DIRECT);

        // 声明死信队列
        String deadQueue = "dead-queue";
        channel.queueDeclare(deadQueue, false, false, false, null);
        // 死信队列绑定死信交换机与  routingkey
        channel.queueBind(deadQueue, DEAD_EXCHANGE, ROUTING_KEY);

        //正常队列绑定死信队列信息
        Map<String, Object> params = new HashMap<>();
        //正常队列设置死信交换机   参数  key是固定值
        params.put("x-dead-letter-exchange", DEAD_EXCHANGE);
        //正常队列设置死信  routing-key 参数  key是固定值
        params.put("x-dead-letter-routing-key", ROUTING_KEY);

        // TODO 如果是演示`队列达到最大长度`的情况，需要设置最大队列数量
        // params.put("x-max-length", 6);

        // 声明正常队列
        String normalQueue = "normal-queue";
        channel.queueDeclare(normalQueue, false, false, false, params);
        channel.queueBind(normalQueue, NORMAL_EXCHANGE, NORMAL_ROUTING_KEY);

        System.out.println("Consumer01等待接收消息.....");
        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            // TODO 正常接收消息
            // System.out.println("Consumer01接收到消息" + message);
            // channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            // TODO 模拟拒绝接收进入死信队列
            if (message.equals("info5")) {
                System.out.println("Consumer01接收到消息" + message + "并拒绝签收该消息");
                //requeue设置为  false 代表拒绝重新入队   该队列如果配置了死信交换机将发送到死信队列中
                channel.basicReject(delivery.getEnvelope().getDeliveryTag(), false);
            } else {
                System.out.println("Consumer01接收到消息" + message);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        channel.basicConsume(normalQueue, false, deliverCallback, consumerTag -> {
        });
    }
}
